package com.ruoyi.testing.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.customerSample.domain.Customer;
import com.ruoyi.customerSample.mapper.CustomerMapper;
import com.ruoyi.report.domain.Bgbh;
import com.ruoyi.report.mapper.BgbhMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.testing.domain.EntrustmentAgreement;
import com.ruoyi.testing.domain.EntrustmentAgreementDetail;
import com.ruoyi.testing.domain.OaDispath;
import com.ruoyi.testing.mapper.EntrustmentAgreementDetailMapper;
import com.ruoyi.testing.mapper.EntrustmentAgreementMapper;
import com.ruoyi.testing.mapper.OaDispathMapper;
import com.ruoyi.testing.service.IEntrustmentAgreementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 委托协议Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-10-16
 */
@Service
public class EntrustmentAgreementServiceImpl implements IEntrustmentAgreementService
{
    @Autowired(required = false)
    private EntrustmentAgreementMapper entrustmentAgreementMapper;

    @Autowired(required = false)
    private EntrustmentAgreementDetailMapper entrustmentAgreementDetailMapper;

    @Autowired(required = false)
    private CustomerMapper customerMapper;

    @Autowired(required = false)
    private OaDispathMapper oaDispathMapper;

    @Autowired(required = false)
    private SysUserMapper sysUserMapper;

    @Autowired(required = false)
    private BgbhMapper bgbhMapper;

    /**
     * 查询委托协议
     * 
     * @param id 委托协议主键
     * @return 委托协议
     */
    @Override
    public EntrustmentAgreement selectEntrustmentAgreementById(String id)
    {
        EntrustmentAgreement entrustmentAgreement = entrustmentAgreementMapper.selectEntrustmentAgreementById(id);
        if(null != entrustmentAgreement) {
            //获取明细信息
            EntrustmentAgreementDetail entrustmentAgreementDetail = new EntrustmentAgreementDetail();
            entrustmentAgreementDetail.setAgreementId(id);
            List<EntrustmentAgreementDetail> entrustmentAgreementDetails = entrustmentAgreementDetailMapper.selectEntrustmentAgreementDetailList(entrustmentAgreementDetail);
            entrustmentAgreementDetails.forEach(item ->{
                List<Map<String, Object>> bgbhList = new ArrayList<>();
                if(StringUtils.isNotEmpty(item.getNums())) {
                    if(Integer.valueOf(item.getNums()) > 1) {
                        //截取首个编号
                        String start = StringUtils.substringBetween(item.getReportNum(), "(", "-");
                        //报告编号前半段
                        String preBgbh = StringUtils.substring(item.getReportNum(), 0, item.getReportNum().indexOf("("));
                        for (int i = 0; i < Integer.valueOf(item.getNums()); i++) {
                            Map<String, Object> bgbhMap = new HashMap<>();
                            bgbhMap.put("reportNum", preBgbh + String.format("%04d",(Integer.valueOf(start) + i)));
                            bgbhList.add(bgbhMap);
                        }
                        item.setBgbhList(bgbhList);
                    }
                }
            });
            entrustmentAgreement.setList(entrustmentAgreementDetails);
        }
        return entrustmentAgreement;
    }

    /**
     * 查询项目编号
     */
    @Override
    public List<String> selectEntrustmentAgreementNum() {
        return entrustmentAgreementMapper.selectEntrustmentAgreementNum();
    }

    /**
     * 查询委托协议
     *
     * @param agreementNum 项目编号
     * @return 委托协议
     */
    @Override
    public EntrustmentAgreement selectEntrustmentAgreementByNum(String agreementNum) {
        return entrustmentAgreementMapper.selectEntrustmentAgreementByNum(agreementNum);
    }


    /**
     * 根据项目类别和年份获取最大编号
     * @param itemType
     * @param itemYear
     * @return
     */
    @Override
    public String selectAgreementNumMax(String itemType, String itemYear) {
        //获取当前最大项目编号
        Integer maxAgreementNum = entrustmentAgreementMapper.selectAgreementNumMax(itemType, itemYear);
        if(maxAgreementNum == null){
            maxAgreementNum = 0;
        }
        if(StringUtils.equals("JK", itemType)) {
            return "FM-"  + itemYear + "-"  + String.format("%02d", maxAgreementNum + 1) + "-AN";
        }else if(StringUtils.equals("MK", itemType)) {
            return "M-"  + itemYear + "-"  + String.format("%02d", maxAgreementNum + 1) + "-AN";
        }
        return "派工单号生成失败！";
    }

    /**
     * 查询委托协议列表
     * 
     * @param entrustmentAgreement 委托协议
     * @return 委托协议
     */
    @Override
    public List<EntrustmentAgreement> selectEntrustmentAgreementList(EntrustmentAgreement entrustmentAgreement)
    {
        List<EntrustmentAgreement> entrustmentAgreements = entrustmentAgreementMapper.selectEntrustmentAgreementList(entrustmentAgreement);
        if(entrustmentAgreements.size() > 0) {
            for(EntrustmentAgreement e : entrustmentAgreements) {
                //获取明细信息
                EntrustmentAgreementDetail entrustmentAgreementDetail = new EntrustmentAgreementDetail();
                entrustmentAgreementDetail.setAgreementId(e.getId());
                List<EntrustmentAgreementDetail> entrustmentAgreementDetails = entrustmentAgreementDetailMapper.selectEntrustmentAgreementDetailList(entrustmentAgreementDetail);
                entrustmentAgreementDetails.forEach(item ->{
                    List<Map<String, Object>> bgbhList = new ArrayList<>();
                    if(StringUtils.isNotEmpty(item.getNums())) {
                        if(Integer.valueOf(item.getNums()) > 1) {
                            //截取首个编号
                            String start = StringUtils.substringBetween(item.getReportNum(), "(", "-");
                            //报告编号前半段
                            String preBgbh = StringUtils.substring(item.getReportNum(), 0, item.getReportNum().indexOf("("));
                            for (int i = 0; i < Integer.valueOf(item.getNums()); i++) {
                                Map<String, Object> bgbhMap = new HashMap<>();
                                bgbhMap.put("reportNum", preBgbh + String.format("%04d",(Integer.valueOf(start) + i)));
                                bgbhList.add(bgbhMap);
                            }
                            item.setBgbhList(bgbhList);
                        }
                    }
                });
                e.setList(entrustmentAgreementDetails);
            }
        }
        return entrustmentAgreements;
    }

    /**
     * 新增委托协议
     * 
     * @param entrustmentAgreement 委托协议
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertEntrustmentAgreement(EntrustmentAgreement entrustmentAgreement)
    {
        //判断是否存在项目编号，存在清空
        if(StringUtils.isNotEmpty(entrustmentAgreement.getAgreementNum())) {
            //清空原委托协议信息
            entrustmentAgreementMapper.deleteEntrustmentAgreementById(entrustmentAgreement.getId());
            entrustmentAgreementDetailMapper.deleteEntrustmentAgreementDetailByNum(entrustmentAgreement.getId());
            //删除原派工单
            oaDispathMapper.deleteOaDispathByAId(entrustmentAgreement.getId());
            //删除原报告编号
            bgbhMapper.deleteBgbhByANum(entrustmentAgreement.getAgreementNum());
        }
        //根据项目类型获取当前最大项目编号
        Integer agreementMaxNum = entrustmentAgreementMapper.selectAgreementNumMax(entrustmentAgreement.getItemType(), DateUtils.getYear());
        String agreementNum = "";
        if(agreementMaxNum == null){
            //初始化项目编号
            agreementNum = entrustmentAgreement.getItemType() + "-"  + DateUtils.getYear() + "-01";
        }else {
            //项目编号+1
            agreementNum = entrustmentAgreement.getItemType() + "-"  + DateUtils.getYear() + "-"  + String.format("%02d", agreementMaxNum + 1);
        }
        entrustmentAgreement.setAgreementNum(agreementNum);
        String id = IdUtils.fastSimpleUUID();
        entrustmentAgreement.setId(id);
        entrustmentAgreement.setItemYear(DateUtils.getYear());
        entrustmentAgreement.setState("1");
        //新增项目信息
        int ret = entrustmentAgreementMapper.insertEntrustmentAgreement(entrustmentAgreement);
        //新增明细信息
        if(ret > 0 && entrustmentAgreement.getList().size() > 0) {
            for(EntrustmentAgreementDetail entrustmentAgreementDetail : entrustmentAgreement.getList()) {
                entrustmentAgreementDetail.setAgreementId(id);
                entrustmentAgreementDetail.setState("1");
                entrustmentAgreementDetail.setSubTester(StringUtils.join(entrustmentAgreementDetail.getSubTesters(), ","));
                entrustmentAgreementDetail.setAgreementNum(entrustmentAgreement.getAgreementNum());
                entrustmentAgreementDetail.setId(IdUtils.fastSimpleUUID());
            }
            entrustmentAgreementDetailMapper.insertDetails(entrustmentAgreement.getList());
        }
        //新增任务单据
        if(ret > 0){
            //消息通知任务(批量推送)
            List<OaDispath> oaDispathList = new ArrayList<OaDispath>();
            //根据检测项目明细推送
            for(EntrustmentAgreementDetail detail : entrustmentAgreement.getList()) {
                //获取明细人员信息
                String[] subTesters =detail.getSubTesters();
                List<String> testers = new ArrayList<>();
                if(subTesters.length > 0) {
                    testers = new ArrayList<>(Arrays.asList(subTesters));
                }
                for(int i = 0; i < testers.size(); i++) {
                    OaDispath oaDispath = new OaDispath();
                    oaDispath.setId(IdUtils.fastSimpleUUID());
                    oaDispath.setAgreementId(entrustmentAgreement.getId());
                    oaDispath.setAgreementNum(entrustmentAgreement.getAgreementNum());
                    oaDispath.setAdress(entrustmentAgreement.getCompanyAdress());
                    oaDispath.setStartTime(entrustmentAgreement.getPlanTime());
                    oaDispath.setEndTime(entrustmentAgreement.getTestDate());
                    oaDispath.setTitle(entrustmentAgreement.getCompanyName() + "(" + entrustmentAgreement.getAgreementNum()  + "-" + DictUtils.getDictLabel(entrustmentAgreement.getItemType().toLowerCase(), detail.getSampleType(), "")  +")" + "检测任务");
                    if(StringUtils.isNotEmpty(testers.get(0))) {
                        oaDispath.setTestRole("主检");
                    }else {
                        oaDispath.setTestRole("副检");
                    }
                    oaDispath.setTestId(testers.get(i));
                    oaDispath.setTester(sysUserMapper.selectUserById(Long.valueOf(testers.get(i))).getUserName());
                    oaDispath.setState("1");
                    oaDispath.setCreater(entrustmentAgreement.getTaskDistributionPeople());
                    oaDispath.setCreatime(DateUtils.getNowDate());
                    oaDispathList.add(oaDispath);
                }
            }
            if(null !=oaDispathList &&  !oaDispathList.isEmpty()) {
                oaDispathMapper.insertOaDispaths(oaDispathList);
            }
        }
        //查询委托单位是否存在，不存在则添加
        Customer c = new Customer();
        c.setCompanyName(entrustmentAgreement.getCompanyName());
        c.setAdress(entrustmentAgreement.getCompanyAdress());
        List<Customer> reportCompanyList = customerMapper.selectCustomerList(c);
        if(null == reportCompanyList) {
            Customer customer = new Customer();
            customer.setId(IdUtils.fastSimpleUUID());
            customer.setCompanyName(entrustmentAgreement.getCompanyName());
            customer.setCompanyShortname(entrustmentAgreement.getReportName());
            customer.setAdress(entrustmentAgreement.getCompanyAdress());
            customer.setCharger(entrustmentAgreement.getCompanyCharge());
            customer.setChargerPhone(entrustmentAgreement.getChargePhone());
            customerMapper.insertCustomer(customer);
        }
        //新增报告编号信息
        if(null != entrustmentAgreement.getList() && !entrustmentAgreement.getList().isEmpty()) {
            entrustmentAgreement.getList().forEach(item ->{
                //获取当前检测项目最大报告编号信息
                Integer reportNum = bgbhMapper.selectBgbhMax(item.getSampleType());
                if(StringUtils.isNotEmpty(item.getNums())) {
                    //获取报告数量
                    if (Integer.valueOf(item.getNums()) > 1) {
                        //截取首个编号
                        String start = StringUtils.substringBetween(item.getReportNum(), "(", "-");
                        //报告编号前半段
                        String preBgbh = StringUtils.substring(item.getReportNum(), 0, item.getReportNum().indexOf("("));
                        List<Bgbh> bgbhList = new ArrayList<>();
                        for (int i = 0; i < Integer.valueOf(item.getNums()); i++) {
                            Bgbh bgbh = new Bgbh();
                            bgbh.setId(IdUtils.fastSimpleUUID() + i);
                            bgbh.setCustomer(entrustmentAgreement.getCompanyName());
                            bgbh.setType(entrustmentAgreement.getItemType());
                            bgbh.setEquName(item.getSampleType());
                            bgbh.setNums(item.getNums());
                            bgbh.setMainTester(item.getMainTester());
                            bgbh.setBgbh(preBgbh + String.format("%04d", (Integer.valueOf(start) + i)));
                            bgbh.setTestPlace(entrustmentAgreement.getCompanyAdress());
                            bgbh.setArea(entrustmentAgreement.getReportName());
                            bgbh.setSubTester(item.getSubTester());
                            bgbh.setTestDate(entrustmentAgreement.getTestDate());
                            bgbh.setAgreementNum(entrustmentAgreement.getAgreementNum());
                            bgbh.setYears(entrustmentAgreement.getItemYear());
                            bgbhList.add(bgbh);
                        }
                        bgbhMapper.insertBgbhs(bgbhList);
                    } else {
                        Bgbh bgbh = new Bgbh();
                        bgbh.setId(IdUtils.fastSimpleUUID());
                        bgbh.setCustomer(entrustmentAgreement.getCompanyName());
                        bgbh.setType(entrustmentAgreement.getItemType());
                        bgbh.setEquName(item.getSampleType());
                        bgbh.setNums(item.getNums());
                        bgbh.setMainTester(item.getMainTester());
                        bgbh.setBgbh(item.getReportNum());
                        bgbh.setTestPlace(entrustmentAgreement.getCompanyAdress());
                        bgbh.setArea(entrustmentAgreement.getReportName());
                        bgbh.setSubTester(item.getSubTester());
                        bgbh.setTestDate(entrustmentAgreement.getTestDate());
                        bgbh.setAgreementNum(entrustmentAgreement.getAgreementNum());
                        bgbh.setYears(entrustmentAgreement.getItemYear());
                        bgbhMapper.insertBgbh(bgbh);
                    }
                }
            });
        }
        return ret;
    }

    /**
     * 修改委托协议
     * 
     * @param entrustmentAgreement 委托协议
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateEntrustmentAgreement(EntrustmentAgreement entrustmentAgreement)
    {
        //更新协议
        int ret = entrustmentAgreementMapper.updateEntrustmentAgreement(entrustmentAgreement);
        if(ret > 0 && entrustmentAgreement.getList().size() > 0) {
            //删除原有数据
            int dRet = entrustmentAgreementDetailMapper.deleteEntrustmentAgreementDetailByNum(entrustmentAgreement.getId());
            //新增数据
            if (ret > 0 && entrustmentAgreement.getList().size() > 0) {
                for (EntrustmentAgreementDetail entrustmentAgreementDetail : entrustmentAgreement.getList()) {
                    entrustmentAgreementDetail.setAgreementId(entrustmentAgreement.getId());
                    entrustmentAgreementDetail.setState("1");
                    entrustmentAgreementDetail.setAgreementNum(entrustmentAgreement.getAgreementNum());
                    entrustmentAgreementDetail.setId(IdUtils.fastSimpleUUID());
                }
                entrustmentAgreementDetailMapper.insertDetails(entrustmentAgreement.getList());
            }
        }
        return ret;
    }

    /**
     * 变更委托单状态
     * @param state
     * @param agreementNum
     * @return
     */
    @Override
    public int updateEntrustmentStateByNum(String state, String agreementNum) {
        return entrustmentAgreementMapper.updateEntrustmentStateByNum(state, agreementNum);
    }

    /**
     * 批量删除委托协议
     * 
     * @param ids 需要删除的委托协议主键
     * @return 结果
     */
    @Override
    public int deleteEntrustmentAgreementByIds(String[] ids)
    {
        for(int i = 0 ; i < ids.length; i++) {
            return deleteEntrustmentAgreementById(ids[i]);
        }
        return  1;
    }

    /**
     * 删除委托协议信息
     * 
     * @param id 委托协议主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEntrustmentAgreementById(String id)
    {
        //根据Id获取委托协议信息
        EntrustmentAgreement entrustmentAgreement = selectEntrustmentAgreementById(id);
        int ret = entrustmentAgreementMapper.deleteEntrustmentAgreementById(id);
        if(ret > 0) {
            entrustmentAgreementDetailMapper.deleteEntrustmentAgreementDetailByNum(id);
        }
        //删除原派工单
        oaDispathMapper.deleteOaDispathByAId(id);
        //删除原报告编号
        bgbhMapper.deleteBgbhByANum(entrustmentAgreement.getAgreementNum());
        return ret;
    }
}
